import React, { useMemo, useRef } from "react"
import Taro from "@tarojs/taro"
import { /** Image, **/ Text, View } from "@tarojs/components"
import clsx from "clsx"
import GpIcon from "@/components/GpFontIcon"
import { qaDoLike } from "@/apis/index"

type IProps = {
  className?: string
  /** 用户头像 现在暂用iconfont假头像，所以这里给颜色就行先 */
  avatar: string
  content: string
  symbolText: React.ReactNode
  /** 是否允许点赞 */
  allowSupport?: boolean
  /** 点赞成功时触发，参数为当前item的key */
  onSupport?: (key?: string | number) => any
  supportCount?: number
  /** 是否点赞过 */
  supported?: boolean
  itemKey?: string | number
}
const iconSize = Taro.pxTransform(32)
const GpQAContentItem: React.FC<IProps> = (props: IProps) => {
  const pending = useRef(false)
  const {
    className,
    avatar,
    content,
    symbolText,
    allowSupport,
    supportCount,
    onSupport,
    supported,
    itemKey
  } = props
  const renderContent = useMemo(() => {
    if (!content) return content
    return content.replace(/\<br\s?\/\>/gi, function () {
      return "\n"
    })
  }, [content])
  function handleClick() {
    if (supported) {
      Taro.showToast({
        title: "你已经点过赞了",
        icon: "none"
      })
      return
    }
    if (pending.current) return
    qaDoLike(itemKey as any)
      .then(res => {
        if (res.data.success) {
          Taro.showToast({
            title: "点赞成功",
            icon: "none"
          })
          onSupport && onSupport(itemKey)
        }
      })
      .finally(() => {
        pending.current = true
      })
  }
  return (
    <View className={clsx("flex flex-col", className)}>
      <View className="flex flex-row items-center">
        {/* <Image src={avatar} className="w-56px h-56px rounded-1" /> */}
        {/* 暂时用假头像 */}
        <GpIcon icon="icon-touxiang" size={64} color={avatar} />
        <Text className="yahei-bold font-bold text-28px text-hex-2c2c35 ml-16px">{symbolText}</Text>
      </View>
      <Text
        className="yahei font-normal text-28px text-hex-666 leading-48px mt-20px inline-block break-all text-justify"
        decode
        userSelect
      >
        {renderContent}
      </Text>
      {/* 点赞 */}
      {allowSupport && (
        <View className="yahei font-normal text-28px text-hex-b8b8bf mt-31px text-right mt-20px">
          <GpIcon
            icon="icon-youshimianxing"
            color={supported ? "#1A8CFF" : "#B8B8BF"}
            size={iconSize}
            onClick={handleClick}
          />
          {supportCount}
        </View>
      )}
    </View>
  )
}
export default GpQAContentItem
